package com.hserver.deploy.config;

import com.hserver.deploy.utils.FileUtil;
import com.hserver.deploy.utils.SqliteHelper;
import org.beetl.sql.core.*;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import top.hserver.core.ioc.annotation.Bean;
import top.hserver.core.ioc.annotation.Configuration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

@Configuration
public class SqlConfig {

    @Bean
    public SQLManager sql() throws Exception {
        String path = System.getProperty("user.dir") + File.separator + "db.db";
        File file = new File(path);
        boolean flag=false;
        if (!file.exists()) {
            //进行导出初始化一个sqlite
            InputStream is = SqlConfig.class.getResourceAsStream("/db/db.db");
            FileUtil.copyFile(is,path);
            flag=true;
        }
        String url = "jdbc:sqlite:" + path;
        String driver = "org.sqlite.JDBC";
        ConnectionSource source = ConnectionSourceHelper.getSimple(driver, url, null, null);
        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        SQLLoader loader = new ClasspathLoader("/sql");
        // 数据库命名跟java命名一样，所以采用DefaultNameConversion，还有一个是UnderlinedNameConversion，下划线风格的，
        UnderlinedNameConversion nc = new UnderlinedNameConversion();
        // 最后，创建一个SQLManager,DebugInterceptor 不是必须的，但可以通过它查看sql执行情况
        SQLManager sqlManager = new SQLManager(mysql, loader, source, nc, new Interceptor[]{new DebugInterceptor()});
        if (flag){
            //初始化一些表格
            SqliteHelper sqliteHelper=new SqliteHelper();
            sqliteHelper.executeUpdate(InitSqlConfig.sqls);
        }
        return sqlManager;
    }


}
